package com.gljx.web.service.impl;

import com.gljx.constant.ActivitiKey;
import com.gljx.util.ActitiviUtil;
import com.gljx.util.GetUserSession;
import com.gljx.util.ServerResponse;
import com.gljx.web.Entity.ExitClazz;
import com.gljx.web.Entity.Message;
import com.gljx.web.Entity.Student;
import com.gljx.web.dao.CommonDao;
import com.gljx.web.dao.ExitClazzMapper;
import com.gljx.web.dao.StudentMapper;
import com.gljx.web.service.ExitClazzService;
import com.gljx.web.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ExitClazzServiceImpl extends CommonDao implements ExitClazzService {
	
	@Autowired
	private ExitClazzMapper exitClazzMapper;

	@Autowired
	private StudentMapper studentMapper;

	@Autowired
	private MessageService messageService;


	//导入activiti工具
	ActitiviUtil activitiUtil = new ActitiviUtil();

	//1.提交
	//用户点击提交按钮时我们将流程创建出来
	public void submitFlow(ExitClazz exitClazz, String submitFlag,HttpServletRequest request) {
		//1.这里是你修改单据的代码，此处你应该有一个单据


		//2.将这个单据编号和你需要保存的流程变量存入map集合中
		Map<String,Object> map = new HashMap<String,Object>();

		map.put(ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_exitClazz_gl : ActivitiKey.DrivingSys_exitClazz_nc,exitClazz.getFnumber());//使用你自己单据的key，或者用默认的
		/*com.gljx.constant.ActivitiKey 中存入流程相关的常量，最好将流程定义的key也存入其中*/
		if(exitClazz.getDeptName().equals("营销部")){
			map.put(ActivitiKey.deptId, "123");
		}else {
			map.put(ActivitiKey.deptId, "1");
		}



		if (activitiUtil.notTask.equals(submitFlag)) {
			//3.调用方法
			String piID = activitiUtil.creatFlow(
					ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_exitClazz_gl : ActivitiKey.DrivingSys_exitClazz_nc,  //指定要启动的流程定义
					map                     //流程变量
			);

			//4.如果你有“提交”这个流程，那么你还要补上一步，将流程推进到提交的下一步
			Message message = activitiUtil.completeFlowByPiID(piID);
			if (message != null) {
				message.setMessage("退学申请-审核 "+exitClazz.getFnumber());//消息内容
				message.setUrl("/selExitClazzById?fid=" + exitClazz.getFid());//详细路径
				message.setEditUrl("/checkExitClazzBillState?fid=" + exitClazz.getFid()+"&fnumber=" + exitClazz.getFnumber());
				messageService.insert(message);
			}

			///////////////////////////////        二、当前有进行的流程       ///////////////////////////
			/////////////////////////////////////////////////////////////////////////////////////////

			/*详情页获取单据是否有历史记录，放到前台，然后取回 传到提交方法中判断*/
		}else if (activitiUtil.FINISH.equals(submitFlag)) {
			//3.调用方法
			String piID = activitiUtil.creatFlow(
					ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_exitClazz_gl : ActivitiKey.DrivingSys_exitClazz_nc,  //指定要启动的流程定义
					map                     //流程变量
			);

			//4.如果你有“提交”这个流程，那么你还要补上一步，将流程推进到提交的下一步
			Message message = activitiUtil.completeFlowByPiID(piID);
			if (message != null) {
				message.setMessage("退学申请-审核 "+exitClazz.getFnumber());//消息内容
				message.setUrl("/selExitClazzById?fid=" + exitClazz.getFid());//详细路径
				message.setEditUrl("/checkExitClazzBillState?fid=" + exitClazz.getFid()+"&fnumber=" + exitClazz.getFnumber());
				messageService.insert(message);
			}
		} else{
			/*审核过程中的单据被打回调此方法*/
			Message message2 = activitiUtil.complteFlowByVariable(
					ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_exitClazz_gl : ActivitiKey.DrivingSys_exitClazz_nc,  //指定要启动的流程定义
					exitClazz.getFnumber()                     //流程变量
			);

			if (message2 != null) {
				message2.setMessage("退学申请-审核 "+exitClazz.getFnumber());//消息内容
				message2.setUrl("/selExitClazzById?fid=" + exitClazz.getFid());//详细路径
				message2.setEditUrl("/checkExitClazzBillState?fid=" + exitClazz.getFid()+"&fnumber=" + exitClazz.getFnumber());
				messageService.insert(message2);
			}
		}
	}


    //2.审核
	//用户点击审核按钮时的操作
	public String checkFlow(ExitClazz exitClazz, String agreed, String auditcomment,HttpServletRequest request) {
		//1.获取页面传来的单据ID

		//2.根据单据来推进指定流程

		//2.1审核有两种情况同意与不同意，不同意可能有批注
		if("2".equals(agreed)) {
			if (auditcomment == null) {
				auditcomment = "不同意：";
			} else {
				auditcomment = "不同意：" + auditcomment;
			}
		} else {
			if(auditcomment == null){
				auditcomment = "同意：";
			}else {
				auditcomment = "同意：" + auditcomment;
			}
		}
		//2.2使用这个方法必须保证usertask节点与其子连线key值符合要求
		Object returnMsg =
				activitiUtil
						.auditComplteMessage(
								ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_exitClazz_gl : ActivitiKey.DrivingSys_exitClazz_nc,
								exitClazz.getFnumber(),                  //单据
								Integer.valueOf(agreed),                 //1、0是否同意取决于你的流程图
								auditcomment              //批注，直接把前端传过来的string塞进来
						);
		if(returnMsg instanceof Message){
			Message resultMsg = (Message) returnMsg;
			resultMsg.setMessage("退学申请-审核 "+exitClazz.getFnumber());//消息内容
			resultMsg.setUrl("/selExitClazzById?fid=" + exitClazz.getFid());//详细路径
			resultMsg.setEditUrl("/checkExitClazzBillState?fid=" + exitClazz.getFid()+"&fnumber=" + exitClazz.getFnumber());
			messageService.insert(resultMsg);
			return "审核成功!";
		} else if(activitiUtil.notAssign .equals(returnMsg)) {
			return  "当前用户不是要求的经办人";
		} else if(activitiUtil.FINISH.equals(returnMsg)) {
		    exitClazz.setCfbillstate((long)5);
			Student student = new Student();
			        student.setCfstudentstate((long) 11);           //修改学员状态
					student.setFid(exitClazz.getCfstudentid());
			exitClazzMapper.updateByPrimaryKeySelective(exitClazz);
			studentMapper.updateByPrimaryKeySelective(student);
			return  "此流程成功推进，并且此流程已经结束";
		} else if(activitiUtil.SUCCESS.equals(returnMsg)) {
			return  "此流程成功推进";
		} else  {
			return "没有找到正在进行的相关流程";
		}

	}

	//3.反审核
	//用户点击审核按钮时的操作
	public void outTimecheckFlow(ExitClazz exitClazz, HttpServletRequest request) {
		//需要注意反审核按钮是位于流程之外只与权限关联的。
		//这里统一跳提交按钮处
		//同样的流程图需要符合规范

		//1.获取页面传来的单据ID
		/*String danju = "YHTDF202165416531321";*/

		String result = activitiUtil.jumpActivti(
				ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_exitClazz_gl : ActivitiKey.DrivingSys_exitClazz_nc,
				exitClazz.getFnumber()                 //单据
		);
		if(activitiUtil.SUCCESS.equals(result)) {
			System.out.println("成功");
		}else if(activitiUtil.notActiviti.equals(result)) {
			System.out.println("找不到流程节点");
		}else if(activitiUtil.notTask.equals(result)) {
			System.out.println("没有找到任务");
		}
	}


	//4.查询流程状态
	//进入详情页面调用
	public void checkActiviti(ExitClazz exitClazz, HttpServletRequest request) {
		//1.获取页面传来的单据ID
		/*String danju = "YHTDF202165416531321";*/

		//2.查询
		String result = activitiUtil.getTaskStateByUser(
				ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_exitClazz_gl : ActivitiKey.DrivingSys_exitClazz_nc,
				exitClazz.getFnumber()                  //单据
		);

		if(activitiUtil.notTask.equals(result))
		{
			System.out.println("该单据没有对应流程");        //没有历史流程（从来没有过流程的“新单据”）
		}
		else if(activitiUtil.FINISH.equals(result))
		{
			System.out.println("流程已结束");                //只有有历史流程
		}//剩下两种是该任务进行中
		else if(activitiUtil.notAssign.equals(result))
		{
			System.out.println("经办人不匹配");               //正在进行的流程，但是经办人跟当前用户不匹配
		}
		else if(activitiUtil.ISPOWER.equals(result))
		{
			System.out.println("当前用户可以审核该单据");      /**正在进行的流程，且当前用户能够审核
		 * 如果是进入可提交的详情页面，这个标记表示
		 * 此流程进行中，即用户点击提交只需推进流程即可
		 */
		}
	}
	/**
     * 取分页数据    dmz 20160921
     *
     * @param pindex 页码
     * @param psql   SQL语句，需要带 rownum rn 例如：select rownum rn,t.* from zzda t
     * @param psize  每页记录数
     */
    @Override
    public Map<String, Object> selectPage(int pindex, String psql, int psize) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("Pindex", pindex);
        paramMap.put("Psql", psql);
        paramMap.put("Psize", psize);
        paramMap.put("Pcount", oracle.jdbc.OracleTypes.INTEGER);
        paramMap.put("v_cur", oracle.jdbc.OracleTypes.CURSOR);
        this.getSqlSession().select("com.gljx.web.dao.ExitClazzMapper.pagemap", paramMap, null);
        return paramMap;
    }

    /**
     * 取记录总数      dmz 20160921
     *
     * @param psql   SQL语句
     * @return
     */
    @Override
    public Map<String, Object> selectPageCount(String psql) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("Psql", psql);
        paramMap.put("Pcount", oracle.jdbc.OracleTypes.INTEGER);
        this.getSqlSession().select("com.gljx.web.dao.ExitClazzMapper.pagecount", paramMap, null);
        return paramMap;
    }

    
	@Override
	public void insertExitClazz(ExitClazz clazz) {
		// TODO Auto-generated method stub
		exitClazzMapper.insertSelective(clazz);
	}

	@Override
	public void delExitClazzById(String[] fids) {
		// TODO Auto-generated method stub
		exitClazzMapper.delExitClazzById(fids);
	}

	
	@Override
	public ExitClazz selExitClazzById(String fid) {
		// TODO Auto-generated method stub
		return exitClazzMapper.selExitClazzById(fid);
	}

	@Override
	public void updateExitClazz(ExitClazz clazz) {
		// TODO Auto-generated method stub
		exitClazzMapper.updateByPrimaryKeySelective(clazz);
	}

	@Override
	public List<ExitClazz> queryDropoutapply(String companyId) {
		// TODO Auto-generated method stub
		return exitClazzMapper.selectDropoutapply(companyId);
	}

	@Override
	public List<ExitClazz> queryDropoutapplyByName(String companyId, String studentName) {
		// TODO Auto-generated method stub
		Map<String, String> map = new HashMap<>();
		map.put("companyId", companyId);
		map.put("studentName", studentName);
		return exitClazzMapper.selectDropoutapplyByName(map);
	}

	@Override
	public ExitClazz queryDropoutapplyByFid(String fid) {
		// TODO Auto-generated method stub
		return exitClazzMapper.selectDropoutapplyByFid(fid);
	}

    /**
     * 审核
     * @param exitClazz
     * @param 
     * @param state
     * @param agreed
     * @param auditcomment
     * @return
     */
    @Override
    public String checkExitClazz(ExitClazz exitClazz, String state, String agreed, String auditcomment,String submitFlag,HttpServletRequest request) {
        if ("5".equalsIgnoreCase(state)) {
            return checkFlow(exitClazz, agreed, auditcomment,request);
        }
        if ("3".equalsIgnoreCase(state)) {
			uncheckFlow(exitClazz,submitFlag,request,auditcomment);
            exitClazz.setCfbillstate(Long.valueOf("3"));
            exitClazz.setFsourcefunction(auditcomment);
            exitClazzMapper.updateByPrimaryKeySelective(exitClazz);
            return "反审核成功！";
        }
        return null;
    }

	//3.反审核
	//用户点击审核按钮时的操作
	public ServerResponse uncheckFlow(ExitClazz exitClazz , String submitFlag, HttpServletRequest request, String auditcomment) {
		//需要注意反审核按钮是位于流程之外只与权限关联的。
		//这里统一跳提交按钮处
		//同样的流程图需要符合规范
		///////////////////////////////         一、当前没有流程       /////////////////////////////
		/////////////////////////////////////////////////////////////////////////////////////////
		if (activitiUtil.notTask.equals(submitFlag)) {
			//直接修改单据状态为“保存”状态
			Message message2 = activitiUtil.getMessage(
					ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_exitClazz_gl : ActivitiKey.DrivingSys_exitClazz_nc,
					exitClazz.getFnumber()                  //单据
			);

			if (message2 != null) {
				message2.setMessage("退学申请-反审核 "+exitClazz.getFnumber());//消息内容
				message2.setUrl("/selExitClazzById?fid=" + exitClazz.getFid());//详细路径
				messageService.insert(message2);
			}
			return ServerResponse.createBySuccessMessage("反审核成功！");
			///////////////////////////////        二、当前有进行的流程       ///////////////////////////
			/////////////////////////////////////////////////////////////////////////////////////////
		} else {
			Object result = activitiUtil.jumpActivtiMessage(
					ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_exitClazz_gl : ActivitiKey.DrivingSys_exitClazz_nc,
					exitClazz.getFnumber(),                  //单据
					"不同意："+auditcomment
			);
			if (result instanceof Message) {
				Message resultMsg = (Message) result;
						resultMsg.setMessage("退学申请-反审核 "+exitClazz.getFnumber());//消息内容
						resultMsg.setUrl("/selExitClazzById?fid=" + exitClazz.getFid());//详细路径
				messageService.insert(resultMsg);
			} else if (activitiUtil.SUCCESS.equals(result)) {
				System.out.println("成功");

			} else if (activitiUtil.notActiviti.equals(result)) {
				System.out.println("找不到流程节点");

			} else if (activitiUtil.notTask.equals(result)) {
				System.out.println("没有找到任务");
			}
			return ServerResponse.createBySuccessMessage("反审核成功！");
		}
	}
	/**
	 * @Author zyq
	 * @Date 2018/2/7 0007 下午 2:05
	 * 查询经办人是否匹配
	 */
	public String selectAuditPersonByAdd(Object fnumber, String result) {
		if (activitiUtil.notTask.equals(result)) {
			System.out.println("改单据没有对应流程");
			return activitiUtil.notTask;
		} else if (activitiUtil.FINISH.equals(result)) {
			System.out.println("流程已结束");
			return activitiUtil.FINISH;
		}//剩下两种是该任务进行中
		else if (activitiUtil.notAssign.equals(result)) {
			System.out.println("经办人不匹配");
			return activitiUtil.notAssign;
		} else if (activitiUtil.ISPOWER.equals(result)) {
			System.out.println("当前用户可以审核该单据");
			return activitiUtil.ISPOWER;
		} else {
			return "";
		}
	}

}
